package com.idbk.chargestation.activity.user;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.R;
import com.idbk.chargestation.adapter.MyCarAdapter;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonCertification;
import com.idbk.chargestation.bean.JsonCertificationList;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.idbk.chargestation.util.UIUtil;

/**
 * 我的车辆(提交认证后显示)
 * @author liangzw,lupc
 *
 */

public class ActivityMyCar extends BaseActivity implements OnItemClickListener,
OnItemLongClickListener,OnClickListener {

	private SwipeRefreshLayout mSwipeRL;
	private ListView mListView;//爱车信息显示
	private List<JsonCertification> mList;//认证信息集合
	private MyCarAdapter mAdapter;//我的爱车适配器
	private Context mContext;
	
	private LinearLayout mLayoutEmpty, mLayoutError;
	
	private ProgressDialog mDialog;//加载提示框

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_my_car);

		mContext = this;

		setupView();
		
		setupData();
	}

	private void setupView() {
		mSwipeRL = (SwipeRefreshLayout) findViewById(R.id.swipeRL);
		if (mSwipeRL != null) {
			mSwipeRL.setColorSchemeResources(R.color.tj_theme);
		}

		mList = new ArrayList<JsonCertification>();
		mListView = (ListView) findViewById(R.id.my_car_listview);
		mLayoutEmpty = (LinearLayout) findViewById(R.id.layout_empty);
		mLayoutError = (LinearLayout) findViewById(R.id.tj_error_view);
		if (mLayoutError != null) {
			mLayoutError.setOnClickListener(this);
		}

		mAdapter = new MyCarAdapter(mList, mContext);
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(this);
		mListView.setOnItemLongClickListener(this);

		findViewById(R.id.toolbar_back).setOnClickListener(this);
		findViewById(R.id.textview_add).setOnClickListener(this);
		findViewById(R.id.textview_new).setOnClickListener(this);
		
		mSwipeRL.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
			
			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				mMainRequest = ChargeStationAPI.getCertification(mResponse);
			}
		});
	}

	private void setupData() {
		mSwipeRL.post(new Runnable() {
			
			@Override
			public void run() {
				mSwipeRL.setRefreshing(true);
				mMainRequest = ChargeStationAPI.getCertification(mResponse);
			}
		});		
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.toolbar_back:
			finish();
			break;
		case R.id.tj_error_view:
			setupData();
			break;
		case R.id.textview_add:
		case R.id.textview_new:
			addCarCertification();
			break;
		default:
			break;
		}
	}

	private void addCarCertification(){
		//判断是否超过20条验证信息
		if(mList.size() == 20) {
			Toast.makeText(mContext, "最多只能上传20条认证信息", Toast.LENGTH_SHORT).show();
		} else {
			Intent intent = new Intent(mContext, ActivityCertification.class);
			intent.putExtra(Const.CAR_MSG_MODIFY, "false");
			startActivityForResult(intent, 9527);
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == 9527){
			setupData();
		}		
	}

	private void showProgressDialog(){
		if(mDialog == null || !mDialog.isShowing()){
			mDialog = ProgressDialog.show(mContext, null, "加载中...", true, true, new OnCancelListener() {

				@Override
				public void onCancel(DialogInterface dialog) {
					cancelCurrentRequest();
					finish();
				}
			});
		}
	}

	private final EHttpResponse mResponse = new EHttpResponse() {

		@Override
		public void onEResponse(String response) {
			mLayoutError.setVisibility(View.GONE);
			mListView.setVisibility(View.VISIBLE);
			JsonCertificationList result = GsonUtils.toBean(JsonCertificationList.class, response);
			//这里要做一个特殊处理
			if(result != null && result.status == GlobalResult.OBJECT_NOT_FOUND.getStatus()){
				mList.clear();
				UIUtil.showEmpty(mLayoutEmpty, mLayoutError);
				mSwipeRL.setVisibility(View.GONE);
				mAdapter.notifyDataSetChanged();
				return;
			}
			if(handleResponseStatus(ActivityMyCar.this, result)) {
				mList.clear();
				if (result.owenerInfos.size() > 0) {
					mList.addAll(result.owenerInfos);
					UIUtil.hideAll(mLayoutEmpty, mLayoutError);
					mSwipeRL.setVisibility(View.VISIBLE);
				} else {
					UIUtil.showEmpty(mLayoutEmpty, mLayoutError);
					mSwipeRL.setVisibility(View.GONE);
				}
				mAdapter.notifyDataSetChanged();
			}
		}

		@Override
		public void onEErrorResponse(VolleyError error) {
			UIUtil.showNetError(mLayoutEmpty, mLayoutError);
			mSwipeRL.setVisibility(View.GONE);
		}

		@Override
		public void onEFinish() {
			super.onEFinish();
			mSwipeRL.setRefreshing(false);
		}

	};

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) {
		JsonCertification msg = mList.get(position);
		if(msg.checkStatus == JsonCertification.STATE_CERTIFICATION_FAILD){
			Intent intent = new Intent(mContext, ActivityCertification.class);
			intent.putExtra(ActivityCertification.KEY_CERTIFICATION_ACTION, ActivityCertification.ACTION_MODIFY_CERTIFICATION);//判断由此Activity跳转
			intent.putExtra(JsonCertification.KEY, msg);
			startActivity(intent);
		} else {
			Snackbar.make(view, "只能修改 审核失败 的数据！", Snackbar.LENGTH_SHORT).show();
		}		
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent,final View view, final int position,
			long arg3) {			
		final JsonCertification msg = mList.get(position);
		new AlertDialog.Builder(mContext)
		.setMessage("你确定要删除该数据吗？")
		.setNegativeButton(R.string.common_cancel, null)
		.setPositiveButton(R.string.common_ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				if(msg.checkStatus == JsonCertification.STATE_CERTIFICATION_SUCCESS
						|| msg.checkStatus == JsonCertification.STATE_CERTIFICATION_FAILD) {
					deleteCertification(position);//删除认证
				} else {
					Snackbar.make(view, "审核中的数据不能删除！", Snackbar.LENGTH_SHORT).show();
				}							
			}
		})
		.create()
		.show();		
		return true;
	}

	private void deleteCertification(int position) {		
		showProgressDialog();
		int id = mList.get(position).id;
		mMainRequest = ChargeStationAPI.deleteCertification(id, mResponseDelete);
	}

	private final EHttpResponse mResponseDelete = new EHttpResponse() {

		@Override
		public void onEResponse(String response) {
			JsonBase result = GsonUtils.toBean(JsonBase.class, response);
			if(handleResponseStatus(result)) {
				setupData();//重新加载数据
				Toast.makeText(mContext, "删除成功", Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		public void onEErrorResponse(VolleyError error) {			
			Snackbar.make(mListView, "删除失败：网络错误或服务器无响应！", Snackbar.LENGTH_SHORT).show();
		}

		@Override
		public void onEFinish() {
			// 这里要提前调用
			if(mDialog != null){
				mDialog.dismiss();
			}
			super.onEFinish();
		}		

	};

}
